<?php

namespace App\Admin\Middleware;

use App\Admin\Controller\Base\LoginController;
use App\Common\Exception\ApiMessageException;
use App\Common\Util\AdminAuth;
use App\Common\Util\TP;
use Sc\Util\Tool;
use think\Request;
use think\Response;

/**
 * 登录信息认证
 */
class AuthenticateMiddleware
{
    /**
     * @param Request $request
     * @param \Closure $next
     * @return Response
     * @throws ApiMessageException
     */
    public function handle(Request $request, \Closure $next): Response
    {
        if (!AdminAuth::verify() && !str_ends_with(Tool::url($request->url())->getPath(), 'login')) {
            if (str_contains($request->header('accept'), 'application/json')) {
                throw new ApiMessageException("您已退出登录，请重新登录！");
            }

            $url = TP::route()->to([LoginController::class, 'loginView']);
            if ($request->cookie('auth')) {
                $url->setQuery(['auth' => $request->cookie('auth')]);
            }
            return \App\Common\Util\Response::redirect($url);
        }

        return $next($request);
    }
}